package com.category.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.category.entity.DateGroup;
import com.category.mapper.DateGroupMapper;
import com.category.service.DateGroupService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DateGroupServiceImpl extends ServiceImpl<DateGroupMapper, DateGroup> implements DateGroupService {
    
    @Override
    public List<DateGroup> getGroupsByDate(String dateStr) {
        LambdaQueryWrapper<DateGroup> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DateGroup::getDateStr, dateStr)
               .orderByDesc(DateGroup::getCreateTime);
        return list(wrapper);
    }
    
    @Override
    public List<DateGroup> getAllGroups() {
        LambdaQueryWrapper<DateGroup> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(DateGroup::getDateStr)
               .orderByDesc(DateGroup::getCreateTime);
        return list(wrapper);
    }
    
    @Override
    public boolean addGroup(DateGroup dateGroup) {
        // 检查是否已存在相同日期和分类
        LambdaQueryWrapper<DateGroup> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DateGroup::getDateStr, dateGroup.getDateStr())
               .eq(DateGroup::getCategoryId, dateGroup.getCategoryId());
        
        if (count(wrapper) > 0) {
            throw new RuntimeException("该日期下已存在相同的分类");
        }
        
        dateGroup.setCreateTime(LocalDateTime.now());
        dateGroup.setUpdateTime(LocalDateTime.now());
        return save(dateGroup);
    }
    
    @Override
    public boolean deleteGroup(Long id) {
        return removeById(id);
    }
}
